package day06;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//案列
public class A04_Filter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //强转
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;
        //中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取Servlet的映射路径
        String servletPath = req.getServletPath();
        if ("/loginServlet4".equals(servletPath)){
            //放行
            chain.doFilter(req,resp);
        }
        //获取会话域中的数据
        HttpSession session = req.getSession();
        Object username = session.getAttribute("username");
        System.out.println("过滤器执行了吗");
        //判断用户是否登陆
        if (username!=null ){
            chain.doFilter(req,resp);
        }else {
            //跳转到登陆页面
            RequestDispatcher rd = req.getRequestDispatcher("/login/login1.html");
            rd.forward(req,resp);
        }

    }
}
